package 算法;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Description
 *
 * @Author: SunAo
 * @Date: 2022/6/30 15:38
 */
public class 树形转换 {

    static final List<Channel> listData = Arrays.asList(
            new Channel("0001","夜场","-1",null),
            new Channel("0002","酒吧","0001",null),
            new Channel("0003","量贩KTV","0001",null),
            new Channel("0004","商务KTV","0001",null),
            new Channel("0005","夜店","0001",null),
            new Channel("0006","餐饮","-1",null),
            new Channel("0007","高端餐饮","0006",null),
            new Channel("0008","普通餐饮","0006",null),
            new Channel("0009","传统渠道","-1",null),
            new Channel("0010","社会超市","0009",null),
            new Channel("0011","烟酒行","0009",null),
            new Channel("0012","食杂店","0009",null),
            new Channel("0013","现代渠道","-1",null),
            new Channel("0014","大卖场","0013",null),
            new Channel("0015","超市","0013",null),
            new Channel("0016","便利店","0013",null),
            new Channel("0017","高端超市","0013",null)
    );


    /**
     * 树形转换
     * @param basicChannelList
     * @return
     */
    private List<Channel> getTreeAd(List<Channel> basicChannelList) {
        Map<String, Channel> areaMap = new HashMap<>(66);
        for (Channel basicChannel : basicChannelList) {
            areaMap.put(basicChannel.getCode(), basicChannel);
        }
        areaMap.put("-1", new Channel());

        for (Channel basicChannel : basicChannelList) {
            Channel tempChannel = areaMap.get(basicChannel.getParentCode());
            if (tempChannel.getChildren() == null) {
                tempChannel.setChildren(new LinkedList<>());
            }
            tempChannel.getChildren().add(basicChannel);
        }
        return areaMap.get("-1").getChildren();
    }

    @Test
    public void 转换() {
        List<Channel> result = getTreeAd(listData);
        System.out.println(JSON.toJSONString(result));
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Channel{
        private String code;
        private String name;
        private String parentCode;

        private List<Channel> children;
    }
}
